<!DOCTYPE html>
<!--购物车-->
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>购物车</title>
    <link rel="stylesheet" type="text/css" href="../userResource/css/shoppingcart.css">
    <link rel="stylesheet" type="text/css" href="../userResource/css/cart.css">
    <link rel="stylesheet" type="text/css" href="../vendors/myself/floatPanel.min.css">
</head>
<body style="text-align: left;">

<!--头部导入-->
<div id="header"></div>

<div class="nav_bar">
    <div class="wrap">
        <a href="index.html">首页</a>&gt;
        <a href="#">我的购物车</a>
    </div>
</div>

<div class="wrap">
    <div class="cart_list">
        <!--购物车表单-->
        <form id="cartForm" method="post" action="">
            <table cellpadding="0" cellspacing="0">
                <thead>
                <tr>
                    <td class="state">
                        <span class="all_checkbox">
                            <span class="checkbox" onclick="allCheck()"><label class="curr"
                                                                               id="all_check_label"></label></span>
                            <label>全选</label>
                        </span>
                    </td>
                    <td class="name">商品名称</td>
                    <td class="num">数量</td>
                    <td class="prices">价格</td>
                    <td class="prices">总价</td>
                    <td class="operation">操作</td>
                </tr>
                </thead>
                <tbody id="cartListItems">

                </tbody>
            </table>
            <div class="cf total_bar">
                <p class="f_left">
                    <!--<span class="all_checkbox"><span class="checkbox"><label-->
                    <!--class="curr"></label></span><label>全选</label></span>-->
                    <a onclick="deleteChecked()" class="batch-delete" href="javascript:void(0);">删除选中商品</a>
                    <a href="javascript:history.back(-1)">继续购物</a>
                </p>
                <div class="f_right">
                    <div class="f_right">
                        <input type="button" value="去结算" class="btn btn_checkout" onclick="goToBalance()">
                        <p class="tip tip_checkout" style="display: none;"></p>
                    </div>
                    <p class="f_right">共<span id="num"><font id="checkoutNum"></font></span>件商品，　合计：<span>¥<font
                            id="checkoutPrice"></font></span></p>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- iframe -->
<div class="otherPage">
    <!--底部footer-->
    <iframe style="height: 550px" class="page" src="footer.html" scrolling="no" frameborder="no"></iframe>
</div>

<script type="text/javascript" src="../vendors/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../vendors/myself/shoppingcart.js"></script>
<script type="text/javascript" src="../vendors/myself/floatPanel.min.js"></script>

<script type="text/javascript">
    var cartListData = [];
    var isAllCheck = true;
    var panel = FloatPanel('提示');
    var panel2 = FloatPanel('删除提示');

    function setPanel(text) {
        panel.set({
            header: {
                content: "提示",
            },
            body: {content: '<a href="index.html">' + text + '</a>'},
            footer: {enabled: false},
            floatHeight: 20,
            width:228,
        });
    }

    function setPanel2(text) {
        panel2.set({
            header: {
                content: "警告",
            },
            body: {content: text},
            footer: {content: '<button id="delete_btn">确认</button></span>'},
            floatHeight: 20,
            width:228,
        });
    }


    $(function () {
        $('#header').load('header.html');
        $.ajax({
            url: '/user/getLoginedUser',
            type: 'GET',
            success: function (data) {
                if (data.code == 100) {
                    setPanel("请先登录,点击回到主页");
                    panel.show(event);
                    // window.location.href = "/index.html";
                } else {
                    initPage(data);
                }
            }
        })
    })

    function initPage(data) {
        $.ajax({
            url: '/order/getCart',
            type: 'POST',
            data: {'uid': data.rows.uid},
            success: function (data) {
                drawTable(data);
            }
        })
    }

    function drawTable(data) {
        $("#checkoutNum").text(data.rows.allTotal);
        $("#checkoutPrice").text(data.rows.moneyMoney);
        drawListItem(data);
        initCheckbox();

    }

    function drawListItem(data) {
        var cartListItems = $("#cartListItems");
        cartListData = [];

        for (var i = 0; i < data.rows.items.length; i++) {
            var item = data.rows.items[i];
            var itemClone = new Object();
            itemClone.buyNum = item.buyNum;
            itemClone.detailid = item.detailid;
            itemClone.kuid = item.kuid;
            itemClone.pid = item.pid;
            itemClone.price = item.price;
            itemClone.stock = item.stock;
            itemClone.tprice = item.tprice;
            itemClone.isCheck = true;

            cartListData[i] = itemClone;
            // cartListData[i] = item;
            cartListItems.append(
                "<tr id='item_" + item.detailid + "'>\n" +
                "\t<td class=\"state\">\n" +
                "\t\t<span class=\"checkbox\">\n" +
                "\t\t\t<input type=\"checkbox\" id=\"check_" + item.detailid + "\" checked=\"checked\">\n" +
                "\t\t\t<label id=\"check_label_" + item.detailid + "\" class=\"curr\" onclick='changeCheck(" + item.detailid + ")' ></label>\n" +
                "\t\t</span>\n" +
                "\t</td>\n" +
                "\t<td>\n" +
                "\t\t<dl class=\"cf\">\n" +
                "\t\t\t<dt class=\"f_left\"><a href=\"#\" target=\"_blank\"><img src=\"" + item.url + "\" alt=\"\"></a></dt>\n" +
                "\t\t\t<dd class=\"f_left\">\n" +
                "\t\t\t\t<h1 class=\"cf\">\n" +
                "\t\t\t\t\t<a href=\"#\" target=\"_blank\">" + item.pname + "</a>\n" +
                "\t\t\t\t</h1>\n" +
                "\t\t\t</dd>\n" +
                "\t\t</dl>\n" +
                "\t</td>\+n" +
                "\t<td>\n" +
                "\t\t<span class=\"amount number-input\"><span class=\"reduce disable\" onclick='changeBuyNum(" + item.detailid + "," + 0 + ")'></span><input id=\"num_" + item.detailid + "\" name=\"num_" + item.detailid + "\" " +
                "type=\"text\" value=\"" + item.buyNum + "\" onblur=\"inputValidate(" + item.detailid + ")\" ><span class=\"plus\" onclick='changeBuyNum(" + item.detailid + "," + 1 + ")'></span></span>\n" +
                "\t\t<p class=\"stock\">库存<font>" + item.stock + "</font>件</p>\n" +
                "\t</td>\n" +
                "\t<td class=\"price\">¥<font>" + item.price + "</font></td>\n" +
                "\t<td class=\"price\">¥<font id=\"" + "allPrice_" + item.detailid + "\">" + item.moneyTotal + "</font></td>\n" +
                "\t<td><a onclick='removeItem(" + item.detailid + ")' class=\"del\" ><span></span></a></td>\n" +
                "</tr>"
            );

        }

        caculateCost();
    }

    // 结算的点击事件
    function goToBalance() {
        var cart = [];
        for (var i = 0; i < cartListData.length; i++) {
            if (cartListData[i].isCheck) {
                cart[i] = cartListData[i];
            }
        }
        console.log(cart);
        $.ajax({
            url: '/order/goToBalance',
            type: 'POST',
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json',
            data: JSON.stringify(cart),
            success: function (data) {
                console.log(data);
                window.location.href = 'payDetail.html';
            }
        });
    }

    // 全选的点击事件
    function allCheck() {
        console.log(isAllCheck);
        if (isAllCheck) {
            // 全部选中转为全部不选
            for (var i = 0; i < cartListData.length; i++) {
                if (cartListData[i].isCheck) {
                    changeCheck(cartListData[i].detailid);
                    var checkItem = $("#check_label_" + cartListData[i].detailid);
                    checkItem.removeClass("hover");
                    checkItem.removeClass("curr");
                }
            }
        } else {
            // 全部不选转为全选
            for (var i = 0; i < cartListData.length; i++) {
                if (!cartListData[i].isCheck) {
                    changeCheck(cartListData[i].detailid);
                    var checkItem = $("#check_label_" + cartListData[i].detailid);
                    checkItem.addClass("hover");
                    checkItem.addClass("curr");
                }
            }
        }
        caculateCost();
    }

    // -、+图标点击，caculate_type运算类别,0为-,1为+
    function changeBuyNum(detailid, caculate_type) {
        var num = parseInt($("#num_" + detailid).val());
        var item = cartListData[getItemInList(detailid)];
        if (caculate_type == 1) {
            num++;
            console.log(num);
            if (num > item.stock) {
                setPanel("超出库存");
                panel.show(event);
                // alert("超出库存");
                num--;
            }
        } else if (caculate_type == 0) {
            num--;
            if (num < 1) {
                setPanel("数量要大于0");
                panel.show(event);
                // alert("数量要大于0");
                num++;
            }
        }

        $("#num_" + detailid).val(num);
        item.buyNum = num;
        $("#allPrice_" + detailid).text(item.price * num);
        caculateCost();
    }

    // 输入校验
    function inputValidate(detailid) {
        var numStr = $("#num_" + detailid).val();
        var item = cartListData[getItemInList(detailid)];
        if (/^\d+$/.test(numStr)) {
            var num = parseInt(numStr);
            if (num > item.stock) {
                setPanel("数量超过库存");
                panel.show(event);
                // alert("数量超过库存");
                $("#num_" + detailid).val(item.buyNum);
            } else {
                item.buyNum = num;
                caculateCost();
                $("#allPrice_" + detailid).text(item.price * num);
            }
        } else {
            setPanel("只能输入正整数");
            panel.show(event);
            // alert("只能输入正整数");
            $("#num_" + detailid).val(item.buyNum);
        }
    }


    // 移除单项
    function removeItem(detailid) {
        setPanel2("你确定要删除吗?");
        panel2.show();
        $('#delete_btn').click(function () {
            $.ajax({
                url: "/order/delete",
                type: 'POST',
                data: {"detailid": detailid},
                success: function (data) {
                    panel2.hide();
                    setPanel("删除成功");
                    panel.show(event);
                    // alert("删除成功");
                    $("#item_" + detailid).remove();
                    cartListData.splice(getItemInList(detailid), 1);
                    caculateCost();
                },
                fail: function (data) {
                    alert(data.msg);
                }
            });
        });
    }

    // 删除选中
    function deleteChecked() {
        setPanel2("你确定要删除选中的商品吗?")
        panel2.show();
        $('#delete_btn').click(function () {
            var detailids = [];
            for (var i = 0, index = 0; i < cartListData.length; i++, index++) {
                if (cartListData[i].isCheck) {
                    detailids[index] = cartListData[i].detailid;
                }
            }


            $.ajax({
                url: "/order/deleteList",
                type: 'POST',
                contentType: 'application/json',
                datatype: 'json',
                data: JSON.stringify(detailids),
                success: function (data) {
                    for (var i = 0; i < cartListData.length;) {
                        if (cartListData[i].isCheck) {
                            $("#item_" + cartListData[i].detailid).remove();
                            cartListData.splice(i, 1);
                        } else {
                            i++;
                        }
                        panel2.hide();
                        setPanel("删除成功");
                    }
                    caculateCost();
                },
                fail: function (data) {
                    alert(data.msg);
                }
            });
        });
    }

    // 计算全部价格
    function caculateCost() {
        for (var i = 0, sum = 0, num = 0; i < cartListData.length; i++) {
            var item = cartListData[i];
            if (item.isCheck) {
                var buyNum = $("#num_" + item.detailid).val();
                sum += (item.price * buyNum);
                num += parseInt(buyNum);
            }
        }
        changeFootCost(num, sum);
    }

    // 修改选中
    function changeCheck(detailid) {
        var item = cartListData[getItemInList(detailid)];
        item.isCheck = !item.isCheck;// 先取反

        // 再取反就是原来的值
        if (!item.isCheck) {
            $("#all_check_label").removeClass("hover");
            $("#all_check_label").removeClass("curr");
            isAllCheck = false;
        } else {
            var flag = true;
            for (var i = 0; i < cartListData.length; i++) {
                if (!cartListData[i].isCheck) {
                    flag = false;
                }
            }
            if (flag) {
                $("#all_check_label").addClass("hover");
                $("#all_check_label").addClass("curr");
                isAllCheck = true;
            }
        }

        caculateCost();
    }

    // 获取detailid值对应项在数组中的下标值
    function getItemInList(detailid) {
        for (var i = 0; i < cartListData.length; i++) {
            if (cartListData[i].detailid == detailid) {
                return i;
            }
        }
    }

    // 修改最下面的总价和总个数
    function changeFootCost(count, sum) {
        $("#checkoutNum").text(count);
        $("#checkoutPrice").text(sum);
    }
</script>
</body>
</html>